package 多线程;

import org.junit.Test;

import java.util.Scanner;

public class jstack工具类测试 {

    private final static Scanner sca = new Scanner(System.in);

    @Test
    public void 使用jstack查看某一个线程的状态() throws InterruptedException {
        Thread thread = new Thread(()->{
            while(true){
                System.out.println("Hello World");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.setName("jstack-test-thread");
        thread.start();
        thread.join();
        System.out.println("END");
        // 很大概率会看到名为`jstack-test-thread`的线程处于“TIMED_WAITING (sleeping)”状态
    }

    @Test
    public void 状态为NEW的线程(){
        Thread thread = new Thread(()-> System.out.println("Hello World"));
        thread.setName("jstack-test-thread_NEW");
        System.out.println("点击结束");
        sca.nextLine();
        // jstack不会显示状态为NEW的线程
    }

    @Test
    public void 状态为Runable的线程() throws InterruptedException {
        Thread thread = new Thread(()-> {
            while(true){
                System.out.println("Hello World");
            }
        });
        thread.setName("jstack-test-thread_RUNNABLE");
        thread.start();
        thread.join();
        System.out.println("END");
    }

    @Test
    public void 状态为Runable的线程_并且拥有一把锁() throws InterruptedException {
        String message = "haha";
        Thread thread = new Thread(()-> {
            synchronized (message){
                while(true){
                    System.out.println("Hello World");
                }
            }
        });
        thread.setName("jstack-test-thread_LOCED_TEST");
        thread.start();
        thread.join();
        System.out.println("END");
        // 会看到名为`jstack-test-thread_LOCED_TEST`的线程
        // 拥有一个“- locked <0x0000000771b8c9d8> (a java.lang.String)”的锁
    }

    @Test
    public void 模拟线程等待锁的状态() throws InterruptedException {
        Integer a = 1;
        Thread thread1 = new Thread(()->{
           synchronized (a){
               while(true){
                   ;
               }
           }
        });
        Thread thread2 = new Thread(()->{
           synchronized (a){
               while (true){
                   System.out.println("Get Locked at a");
               }
           }
        });
        thread1.setName("Thread-1");
        thread1.start();
        thread2.setName("Thread-2");
        thread2.start();
        thread2.join();
        System.out.println("END");
        // Thread-2 的状态是：java.lang.Thread.State: BLOCKED (on object monitor)
        // 下面的锁显示：waiting to lock <0x000000076d4330e0> (a java.lang.Integer)
    }

}
